﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SDT.Lib.Common;
using System.Linq.Dynamic;
using SDT.Lib.Helpers;
using SDT.Model;
using SDT.Admin.ViewModels;

namespace SDT.Admin.Controllers
{
    [RoleHelper(Roles = RoleSystem.Dictionary)]
    public class CategoryController : Controller
    {
        SDTDataContext eDataContext = new SDTDataContext();

        //
        // GET: /Category/
        public ActionResult Index()
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Dictionary))
                {
                    string order = UserState.getUserStateFromRequest("category.order", "order", "id").ToString();
                    string orderDir = UserState.getUserStateFromRequest("category.orderDir", "orderDir", "desc").ToString();
                    int parentID = Convert.ToInt32(UserState.getUserStateFromRequest("category.parentID", "parentID", 0));
                    var categories = eDataContext.Categories.OrderBy(string.Format("{0} {1}", order, orderDir)).ToList();

                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;

                    return View(new CategoryIndexViewModel
                    {
                        Categories = categories,
                        CurrentParentCategory = parentID
                    });
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Category/Details/5
        public ActionResult Details(int id)
        {
            var cat = eDataContext.Categories.Where(c => c.ID == id).SingleOrDefault();
            return View(cat);
        }

        //
        // GET: /Category/Create
        public ActionResult Create()
        {
            var listParent = eDataContext.Categories.Where(c => c.ParentID == null).ToList();

            return View(new CategoryEditViewModel() { ParrentCatrgories = listParent });
        }

        //
        // POST: /Category/Create
        [HttpPost]
        public ActionResult Create(CategoryEditViewModel c)
        {
            try
            {
                // TODO: Add insert logic here
                UpdateModel(c);
                var pid =Request["ParentID"]!=""? Utils.ParseInt(Request["ParentID"]):0;
                c.Category.ParentID = pid > 0 ? pid : (int?)null;
                c.Category.AddBy = UserManager.GetUserId();
                c.Category.AddDate = DateTime.Now;

                eDataContext.Categories.InsertOnSubmit(c.Category);
                eDataContext.SubmitChanges();

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Category/Edit/5
        public ActionResult Edit(int id)
        {
            var category = eDataContext.Categories.Where(c => c.ID == id).SingleOrDefault();
            var listParent = eDataContext.Categories.Where(c => c.ParentID == null && c.ID != id).ToList();

            return View(new CategoryEditViewModel() { ParrentCatrgories = listParent, Category = category });
        }

        //
        // POST: /Category/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, CategoryEditViewModel c)
        {
            try
            {
                // TODO: Add update logic here
                c.Category = eDataContext.Categories.Where(cat => cat.ID == id).SingleOrDefault();
                UpdateModel(c);
                var pid = Request["ParentID"] != "" ? Utils.ParseInt(Request["ParentID"]) : 0;
                c.Category.ParentID = pid > 0 ? pid : (int?)null;
                c.Category.AddBy = UserManager.GetUserId();
                c.Category.AddDate= DateTime.Now;
                eDataContext.SubmitChanges();

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Department/Delete/5
        public ActionResult Delete(int id)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Dictionary))
                {
                    var item = eDataContext.Categories.Single(e => e.ID == id);
                    return View(item);
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Department/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Dictionary))
                {
                    byte? type = 1;
                    var item = eDataContext.Categories.Single(e => e.ID == id);
                    if (item != null)
                    {
                        eDataContext.Categories.DeleteOnSubmit(item);
                        eDataContext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
    }
}
